# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import urllib2
from deal_info_api import *

def deal_city(tuan, city):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_url = urllib2.urlopen('http://www.meituan.com/api/v1/%s/deals' % (city))

    root_url = ET.fromstring(f_url.read())
    
    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')

    f_xml.write('<deals>\n')

    deals = root_url.getiterator('deal')
    for deal in deals:
	if judge(f_id, d_id, deal, 'id'):
	    continue

	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, 'meituan', '美团网'.decode('utf-8'), 'http://www.meituan.com/', 'http://www.meituan.com/r/i2188')
	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, deal, 'id', 'id', 2)
	deal_info_add(f_xml, deal, 'title', 'name', 2)
	deal_info_cats(f_xml, deal, 'title')
	deal_info_vendor_1(f_xml, deal)
	deal_info_add(f_xml, deal, 'start_date', 'start_time', 2)
	deal_info_add(f_xml, deal, 'end_date', 'end_time', 2)
	deal_info_add(f_xml, deal, 'value', 'o_price', 2)
	deal_info_add(f_xml, deal, 'price', 'c_price', 2)
	deal_info_discount_and_save_money(f_xml, deal, 'price', 'value')
	deal_info_add(f_xml, deal, 'large_image_url', 'img', 2)
	deal_info_add(f_xml, deal, 'deal_url', 'url', 2)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)


f_city = urllib2.urlopen('http://www.meituan.com/api/v1/divisions')
root_city = ET.fromstring(f_city.read())
city_id = root_city.getiterator('id')
for node in city_id:
    deal_city('meituan', node.text)
